<template>
    <div class="container">
        <div class="main" v-show="isOpen">
            <div class="lineParent">
                <div class="left">
                    <canvas ref="canvas" width="1920" height="1080"></canvas>
                </div>
                <div class="line" :style="{ left: linePosition1 + 'px' }" @mousedown="startDrag1" @mousemove="drag1"
                    @mouseup="endDrag1" @mouseleave="endDrag1">
                    <div class="center"></div>
                </div>
                <div class="line" :style="{ left: linePosition2 + 'px' }" @mousedown="startDrag2" @mousemove="drag2"
                    @mouseup="endDrag2" @mouseleave="endDrag2">
                    <div class="center"></div>
                </div>
                <div class="lineY" :style="{ top: linePositionY1 + 'px' }" @mousedown="startDragY1" @mousemove="dragY1"
                    @mouseup="endDragY1" @mouseleave="endDragY1">
                    <div class="center"></div>
                </div>
                <div class="lineY" :style="{ top: linePositionY2 + 'px' }" @mousedown="startDragY2" @mousemove="dragY2"
                    @mouseup="endDragY2" @mouseleave="endDragY2">
                    <div class="center"></div>
                </div>
                <div class="lineRed">{{ form.distanceX }}px</div>
                <div class="lineRed2">{{ form.distanceY }}px</div>
            </div>
            <div class="options">
                <div class="top">
                    <el-button type="danger" :icon="CloseBold" circle @click="closeFile"/>
                </div>
                <el-form :model="form" label-width="auto" style="max-width: 600px">
                    <el-form-item label="画框宽">
                        <el-input v-model="form.width" @keydown.enter="updateCanvasSize" />
                    </el-form-item>
                    <el-form-item label="画框高">
                        <el-input v-model="form.height" @keydown.enter="updateCanvasSize" />
                    </el-form-item>
                    <el-form-item label="缩放比例">
                        <el-input v-model="form.scale" @keydown.enter="changeScale" />
                    </el-form-item>
                    <el-form-item label="网格间隔">
                        <el-input v-model="form.gridInterval" @keydown.enter="updateCanvasSize" />
                    </el-form-item>
                    <el-form-item label="距离X">
                        <el-input v-model="form.distanceX" disabled />
                    </el-form-item>
                    <el-form-item label="距离Y">
                        <el-input v-model="form.distanceY" disabled />
                    </el-form-item>
                    <el-form-item>
                        <!-- <el-button type="primary" size="large" @click="closeFile">关闭</el-button> -->
                        <el-button type="primary" size="large" @click="reDraw">重置</el-button>
                        <!-- <el-button type="primary" size="large" @click="fullScreen">全屏</el-button> -->
                    </el-form-item>
                </el-form>
                <div class="bottom">
                    <el-button type="primary" :icon="FullScreen" circle @click="fullScreen"/>
                </div>
            </div>
        </div>
        <div class="btnBox" v-show="!isOpen">
            <el-button type="primary" size="large" @click="openFile">打开文件</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import {CloseBold,FullScreen} from '@element-plus/icons-vue'
const isOpen = ref(false);
const canvas = ref(null);
const form = reactive({
    width: 1920,
    height: 1080,
    picwidth: 0,
    picheight: 0,
    scale: 1,
    distanceX: 50,
    distanceY: 50,
    gridInterval: 50 // 默认网格间隔为5px
});

const activeLine = ref(0)
const savedImageData = ref(null);
const linePosition1 = ref(50); // 初始位置为200px
const linePosition2 = ref(100); // 初始位置为400px
const linePositionY1 = ref(50); // 初始位置为200px
const linePositionY2 = ref(100); // 初始位置为400px
onMounted(() => {
    document.addEventListener('keydown', function (event) {
        let dom = 0
        if ((event.key === 'ArrowRight' || event.key === 'd')) {
            dom += 1
        } else if ((event.key === 'ArrowLeft' || event.key === 'a')) {
            dom -= 1
        } else if ((event.key === 'ArrowUp' || event.key === 'w')) {
            dom -= 1
        } else if ((event.key === 'ArrowDown' || event.key === 's')) {
            dom += 1
        }
        if (activeLine.value == 1) {
            linePosition1.value += dom
            form.distanceX = Math.abs(linePosition1.value - linePosition2.value) / form.scale;
        } else if (activeLine.value == 2) {
            linePosition2.value += dom
            form.distanceX = Math.abs(linePosition1.value - linePosition2.value) / form.scale;
        } else if (activeLine.value == 3) {
            linePositionY1.value += dom
            form.distanceY = Math.abs(linePositionY1.value - linePositionY2.value) / form.scale;
        } else if (activeLine.value == 4) {
            linePositionY2.value += dom
            form.distanceY = Math.abs(linePositionY1.value - linePositionY2.value) / form.scale;
        }
    });


})
watch(() => isOpen.value, (newVal, oldVal) => {
    nextTick(() => {
        if (newVal) {
            let red1ine = document.getElementsByClassName('lineRed')[0];
            red1ine.style.left = Math.min(linePosition1.value, linePosition2.value) + 'px';
            let blue1 = document.getElementsByClassName('line')[0];
            red1ine.style.top = blue1.offsetHeight / 2 + 'px';

            let red2ine = document.getElementsByClassName('lineRed2')[0];
            let blue3 = document.getElementsByClassName('lineY')[0];
            red2ine.style.left = blue3.offsetWidth / 2 + 'px';
            red2ine.style.top = Math.min(linePositionY1.value, linePositionY2.value) + 'px';
        }
    })
})
watch(() => form.distanceX, (newVal, oldVal) => {
    let red1ine = document.getElementsByClassName('lineRed')[0];
    red1ine.style.left = Math.min(linePosition1.value, linePosition2.value) + 'px';
    red1ine.style.width = Math.abs(linePosition1.value - linePosition2.value) + 'px';
})
watch(() => form.distanceY, (newVal, oldVal) => {
    let red2ine = document.getElementsByClassName('lineRed2')[0];
    red2ine.style.height = Math.abs(linePositionY1.value - linePositionY2.value) + 'px';
    red2ine.style.top = Math.min(linePositionY1.value, linePositionY2.value) + 'px';
})
const closeFile = () => {
    window.electron.ipcRenderer.send('measureClose', JSON.stringify({}));
    isOpen.value = false;
}
const fullScreen = () => {
    window.electron.ipcRenderer.send('measureFullScreen', JSON.stringify({}));
}
const openFile = async () => {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.click();

    fileInput.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
            window.electron.ipcRenderer.send('measureOpen', JSON.stringify({}));
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    isOpen.value = true;
                    const canvasElement = canvas.value;
                    canvasElement.width = img.width;
                    canvasElement.height = img.height; // 设置画布大小
                    const ctx = canvas.value.getContext('2d');
                    // 使用图片的原始宽高绘制图片
                    console.log('img', img.width, img.height);
                    form.width = img.width;
                    form.height = img.height;
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    savedImageData.value = canvas.value.toDataURL(); // 保存图片数据
                    drawGrid(ctx, form.gridInterval); // 绘制网格
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
};

const updateCanvasSize = () => {
    const canvasElement = canvas.value;
    canvasElement.width = parseInt(form.width);
    canvasElement.height = parseInt(form.height);
    // 重新绘制图片和网格
    const ctx = canvasElement.getContext('2d');
    ctx.clearRect(0, 0, canvasElement.width, canvasElement.height); // 清除画布
    drawGrid(ctx, form.gridInterval); // 绘制网格
    const img = new Image();
    img.onload = () => {
        ctx.drawImage(img, 0, 0, parseInt(form.width), parseInt(form.height));
    };
    img.src = savedImageData.value; // 使用保存的图片数据
};
const reDraw = () => {
    // 重新绘制图片和网格
    const img = new Image();
    img.onload = () => {
        form.width = img.width;
        form.height = img.height;
        const canvasElement = canvas.value;
        canvasElement.width = img.width;
        canvasElement.height = img.height;
        const ctx = canvasElement.getContext('2d');
        ctx.clearRect(0, 0, canvasElement.width, canvasElement.height); // 清除画布
        drawGrid(ctx, form.gridInterval); // 绘制网格
        ctx.drawImage(img, 0, 0, img.width, img.height);
    };
    img.src = savedImageData.value; // 使用保存的图片数据
}
const changeScale = () => {
    // 重新绘制图片和网格
    const img = new Image();
    img.onload = () => {
        form.width = img.width * form.scale;
        form.height = img.height * form.scale;
        const canvasElement = canvas.value;
        canvasElement.width = form.width;
        canvasElement.height = form.height;
        const ctx = canvasElement.getContext('2d');
        ctx.clearRect(0, 0, canvasElement.width, canvasElement.height); // 清除画布
        drawGrid(ctx, form.gridInterval); // 绘制网格
        ctx.drawImage(img, 0, 0, form.width, form.height);
    };
    img.src = savedImageData.value; // 使用保存的图片数据
}

const drawGrid = (ctx, interval) => {
    ctx.strokeStyle = '#333'; // 网格线颜色
    ctx.lineWidth = 0.5; // 网格线宽度
    // 绘制横向网格线
    for (let i = 0; i < canvas.value.height; i += parseInt(interval)) {
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(canvas.value.width, i);
        ctx.stroke();
    }

    // 绘制纵向网格线
    for (let i = 0; i < canvas.value.width; i += parseInt(interval)) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, canvas.value.height);
        ctx.stroke();
    }
};

let isDragging1 = false;
let startX1 = 0;

const startDrag1 = (e) => {
    isDragging1 = true;
    startX1 = e.clientX - linePosition1.value;
    activeLine.value = 1
};

const drag1 = (e) => {
    if (isDragging1) {
        const newLeft = e.clientX - startX1;
        linePosition1.value = Math.max(0, Math.min(newLeft, canvas.value.width - 1));
        form.distanceX = Math.abs(linePosition1.value - linePosition2.value) / form.scale;
    }
};

const endDrag1 = () => {
    isDragging1 = false;
};

let isDragging2 = false;
let startX2 = 0;

const startDrag2 = (e) => {
    isDragging2 = true;
    startX2 = e.clientX - linePosition2.value;
    activeLine.value = 2

};

const drag2 = (e) => {
    if (isDragging2) {
        const newLeft = e.clientX - startX2;
        linePosition2.value = Math.max(0, Math.min(newLeft, canvas.value.width - 1));
        form.distanceX = Math.abs(linePosition1.value - linePosition2.value) / form.scale;
    }
};

const endDrag2 = () => {
    isDragging2 = false;
};
let isDraggingY1 = false;
let startY1 = 0;

const startDragY1 = (e) => {
    isDraggingY1 = true;
    startY1 = e.clientY - linePositionY1.value;
    activeLine.value = 3
};

const dragY1 = (e) => {
    if (isDraggingY1) {
        const newTop = e.clientY - startY1;
        linePositionY1.value = Math.max(0, Math.min(newTop, canvas.value.height - 1));
        form.distanceY = Math.abs(linePositionY1.value - linePositionY2.value) / form.scale;
    }
};

const endDragY1 = () => {
    isDraggingY1 = false;
};

let isDraggingY2 = false;
let startY2 = 0;

const startDragY2 = (e) => {
    isDraggingY2 = true;
    startY2 = e.clientY - linePositionY2.value;
    activeLine.value = 4
};

const dragY2 = (e) => {
    if (isDraggingY2) {
        const newTop = e.clientY - startY2;
        linePositionY2.value = Math.max(0, Math.min(newTop, canvas.value.height - 1));
        form.distanceY = Math.abs(linePositionY1.value - linePositionY2.value) / form.scale;
    }
};

const endDragY2 = () => {
    isDraggingY2 = false;
};
</script>

<style lang="less" scoped>
.container {
    width: 100vw;
    height: 100vh;
    padding: 10px;
    border-radius: 10px;
    background-color: #666;

    .btnBox {
        width: 100%;
        height: 100%;
        -webkit-app-region: no-drag;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .main {
        width: 100%;
        height: 100%;
        -webkit-app-region: no-drag;
        display: flex;
        position: relative;

        .options {
            width: 300px;
            height: 100%;
            margin-left: 10px;
            background: #fff;
            border-radius: 10px;
            padding: 10px 20px;
            position: relative;
            z-index: 999;
            display: flex;
            flex-direction: column;
            .top{
                margin-bottom: 20px;
                text-align: end;
            }
            .bottom{
                margin-top: auto;
                text-align: end;
            }

            .linetool {
                width: 30px;
                height: 2px;
                border: 1px solid red;
                cursor: pointer;
            }
        }

        .lineParent {
            flex: 1;
            position: relative;
            display: flex;
            overflow: hidden;
            background: #f1f1f1;

            .lineRed {
                position: absolute;
                top: 50px;
                left: 50px;
                width: 50px;
                height: 20px;
                text-align: center;
                color: red;
                border-top: 1px solid red;
            }

            .lineRed2 {
                position: absolute;
                top: 50px;
                left: 50px;
                width: 50px;
                height: 50px;
                display: flex;
                justify-content: center;
                align-items: center;
                border-left: 1px solid red;
                color: red;
            }

            .line {
                position: absolute;
                top: 0;
                width: 1px;
                height: 100%;
                border: 1px solid #00dbf8;
                cursor: pointer;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                .center {
                    width: 10px;
                    height: 20px;
                    border-radius: 10px;
                    background-color: #00dbf8;

                }

                .center:hover {
                    width: 50px;
                }
            }

            .lineY {
                position: absolute;
                top: 0;
                width: 100%;
                height: 1px;
                border: 1px solid #00dbf8;
                cursor: pointer;
                display: flex;
                justify-content: center;
                align-items: center;

                .center {
                    width: 20px;
                    height: 10px;
                    border-radius: 10px;
                    background-color: #00dbf8;

                }

                .center:hover {
                    height: 50px;
                }
            }

            .left {
                flex: 1;
                border: 1px solid #fff;
                overflow: scroll;

                // 美化滚动条样式
                &::-webkit-scrollbar {
                    width: 8px;
                    height: 8px;
                }

                &::-webkit-scrollbar-thumb {
                    background-color: #333;
                    border-radius: 5px;
                }

                &::-webkit-scrollbar-track {
                    background-color: #f1f1f1;
                    border-radius: 5px;
                }


            }
        }


    }

    .length-display {
        position: absolute;
        bottom: 10px;
        left: 10px;
        background: #fff;
        padding: 5px;
        border-radius: 5px;
    }
}
</style>
